<template>
  <div class="h-full bg-white p-4 overflow-y-auto">
    <div class="flex justify-between items-center mb-4">
      <h2 class="text-lg font-semibold">设计区域</h2>
      <div class="flex gap-2">
        <el-button size="small" @click="exportSchema">导出JSON</el-button>
        <el-button size="small" @click="handleImportSchema">导入JSON</el-button>
        <el-button size="small" @click="preview">预览</el-button>
      </div>
    </div>

    <div
      class="design-container border-2 border-dashed border-gray-300 min-h-96 p-4 rounded-lg"
      @drop="onDrop"
      @dragover="onDragOver"
    >
      <div v-if="!store.currentForm.fields.length" class="text-center text-gray-400 py-12">
        <el-icon size="48" class="mb-2"><Plus /></el-icon>
        <p>拖拽组件到此处或点击左侧物料添加</p>
      </div>

      <div v-if="store.currentForm.fields.length === 0" class="empty-state">
        <div class="text-center text-gray-500 py-12">
          <div class="text-4xl mb-4">📋</div>
          <h3 class="text-lg font-medium mb-2">拖拽物料到此处</h3>
          <p class="text-sm">从左侧物料面板拖拽组件到此处开始设计表单</p>
        </div>
      </div>

      <div v-if="store.currentForm.fields.length === 0" class="empty-state">
        <div class="text-center text-gray-500 py-12">
          <div class="text-4xl mb-4">📋</div>
          <h3 class="text-lg font-medium mb-2">拖拽物料到此处</h3>
          <p class="text-sm">从左侧物料面板拖拽组件到此处开始设计表单</p>
        </div>
      </div>

      <div v-else class="space-y-2">
        <div
          v-for="field in store.currentForm.fields"
          :key="field.id"
          :class="[
            'field-item p-3 border rounded cursor-move transition-all',
            store.selectedField?.id === field.id 
              ? 'border-blue-500 bg-blue-50 shadow-md' 
              : 'border-gray-200 hover:border-gray-300'
          ]"
          @click="selectField(field)"
        >
          <div class="field-preview">
            <div class="field-label text-sm font-medium">{{ field.label }}</div>
            <div class="field-type text-xs text-gray-500">{{ field.type }}</div>
            <div v-if="field.placeholder" class="field-placeholder text-xs text-gray-400 mt-1">
              {{ field.placeholder }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { useDesignerStore } from '../store'
import { getFieldComponent } from '../utils'
import type { FormField } from '../types'

const { store, selectField, exportSchema } = useDesignerStore()

const onDragOver = (event: DragEvent) => {
  event.preventDefault()
  event.dataTransfer!.dropEffect = 'move'
}

const onDragEnd = () => {
  console.log('Drag sorting completed')
}

const onDrop = (event: DragEvent) => {
  event.preventDefault()
  console.log('Drop event received')
  
  // 首先检查全局状态中的拖拽物料
  if (store.dragMaterial) {
    console.log('Material from store:', store.dragMaterial)
    const material = store.dragMaterial
    const field = {
      id: Math.random().toString(36).substr(2, 9),
      ...material.defaultProps
    }
    console.log('Creating field from store:', field)
    store.currentForm.fields.push(field)
    selectField(field)
    store.dragMaterial = null // 清除拖拽状态
    return
  }
  
  // 备用方案：检查dataTransfer
  const dragData = event.dataTransfer?.getData('text/plain')
  console.log('Raw drag data:', dragData)
  
  if (dragData) {
    try {
      const parsedData = JSON.parse(dragData)
      console.log('Parsed drag data:', parsedData)
      
      if (parsedData.type === 'material' && parsedData.data) {
        const material = parsedData.data
        console.log('Material from drag data:', material)
        
        const field = {
          id: Math.random().toString(36).substr(2, 9),
          ...material.defaultProps
        }
        console.log('Creating field from drag data:', field)
        store.currentForm.fields.push(field)
        selectField(field)
        return
      }
    } catch (error) {
      console.error('JSON parse error:', error)
    }
  }
  
  console.log('No valid drag data found')
  // 列出所有可用的数据类型
  const types = event.dataTransfer?.types
  console.log('Available data types:', types)
}

const getFieldProps = (field: FormField) => {
  const baseProps = {
    placeholder: field.placeholder,
    disabled: true
  }

  switch (field.type) {
    case 'select':
      return { ...baseProps, options: field.options }
    case 'radio':
      return { ...baseProps, options: field.options }
    case 'checkbox':
      return { ...baseProps, options: field.options }
    case 'textarea':
      return { ...baseProps, type: 'textarea', rows: field.rows || 3 }
    default:
      return baseProps
  }
}

const preview = () => {
  // 预览功能实现
  console.log('Preview schema:', exportSchema())
}

const handleImportSchema = () => {
  // 导入JSON schema
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = '.json'
  input.onchange = (e) => {
    const file = (e.target as HTMLInputElement).files?.[0]
    if (file) {
      const reader = new FileReader()
      reader.onload = (e) => {
        try {
          const schema = JSON.parse(e.target?.result as string)
          if (validateSchema(schema)) {
            store.currentForm = schema
          } else {
            ElMessage.error('无效的JSON schema格式')
          }
        } catch (error) {
          ElMessage.error('JSON解析错误')
        }
      }
      reader.readAsText(file)
    }
  }
  input.click()
}

const validateSchema = (schema: any): boolean => {
  return !!(schema && Array.isArray(schema.fields))
}
</script>

<style scoped>
.design-container {
  min-height: 500px;
}

.field-item {
  transition: all 0.2s ease;
}

.field-item:hover {
  transform: translateY(-1px);
}
</style>